
package com.gamatechno.solodestinationnew.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.gamatechno.solodestinationnew.BuildConfig;
import com.gamatechno.solodestinationnew.entity.E_Location;
import com.google.android.gms.maps.model.LatLng;

public class Utils {

    private static final String PREF_NAME = "solo_destination_preferences";

    public static final String PREF_BAHASA = "bahasa";
    public static final String PREF_ISLOGIN = "islogin";
    public static final String PREF_FB_ID = "fb_id";
    public static final String PREF_USERNAME = "username";
    private static SharedPreferences sp;

    /**
     * Debuggin method
     * 
     * @param tag TAG
     * @param msg Message out
     */
    public static void TRACE(String tag, String msg) {
        if (BuildConfig.DEBUG)
            Log.d(tag, msg);
    }

    public static void setDataIntTOSP(Context context, String to, int data) {
        Utils.TRACE("Utils", "setDataIntTOSP: " + data);
        sp = context.getSharedPreferences(PREF_NAME, 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(to, data);
        editor.commit();
    }

    public static int getDataIntFromSP(Context context, String from) {
        sp = context.getSharedPreferences(PREF_NAME, 0);
        return sp.getInt(from, 0);
    }

    public static void setDataBooleanToSP(Context context, String to, boolean
            data) {
        Utils.TRACE("Utils", "setDataBooleanToSP: " + data);
        sp = context.getSharedPreferences(PREF_NAME, 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(to, data);
        editor.commit();
    }

    public static boolean getDataBooleanFromSP(Context context, String from)
    {
        sp = context.getSharedPreferences(PREF_NAME, 0);
        return sp.getBoolean(from, false);
    }

    public static void setDataStringToSP(Context context, String to, String
            data) {
        Utils.TRACE("Utils", "setDataStringToSP: " + data);
        sp = context.getSharedPreferences(PREF_NAME, 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(to, data);
        editor.commit();
    }

    public static String getDataStringFromSP(Context context, String from) {
        sp = context.getSharedPreferences(PREF_NAME, 0);
        return sp.getString(from, "");
    }

    public static void setLocale(Context context, String lang) {
        Utils.TRACE("Utils", "setLocale : " + lang);
        // set data to SP
        setDataStringToSP(context, Utils.PREF_BAHASA, lang);
        Locale myLocale;
        myLocale = new Locale(lang);
        Resources res = context.getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);

    }

    /**
     * show volley error
     * 
     * @param context
     * @param error
     */
    public static void showVolleyError(Context context, VolleyError error) {
        if (error instanceof NetworkError) {
            Toast.makeText(context,
                    "Network Error",
                    Toast.LENGTH_SHORT).show();
        } else if (error instanceof ServerError) {
            Toast.makeText(context,
                    "Server Error" + error.networkResponse.statusCode,
                    Toast.LENGTH_SHORT).show();
        } else if (error instanceof NoConnectionError) {
            Toast.makeText(context,
                    "No Connection Error", Toast.LENGTH_SHORT).show();
        } else if (error instanceof TimeoutError) {
            Toast.makeText(context, "NetworkTimeOut", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    /**
     * nilai jarak hanya diberi 1 angka dibelakang koma
     * 
     * @param d nilai yang akan di format
     * @return hasil format
     */
    public static double getRoundTwoDecimal(double d)
    {
        DecimalFormat twoDForm = new DecimalFormat("#.#");
        return Double.valueOf(twoDForm.format(d));
    }

    public static String formatDistance(double d) {
        return String.format(Locale.ENGLISH, "%.2f", d);
    }

    public static double hitungJarak(LatLng posA, LatLng posB)
    {
        float[] result = new float[1];
        Location.distanceBetween(posA.latitude, posA.longitude, posB.latitude,
                posB.longitude, result);

        return result[0];
    }

    /**
     * Sorting jarak halte
     * 
     * @param list list halte
     */
    public static void sortingLocation(List<E_Location> list)
    {
        Collections.sort(list, new Comparator<E_Location>() {
            @Override
            public int compare(E_Location lhs, E_Location rhs)
            {
                return (lhs.getJarak() < rhs.getJarak() ? -1
                        : (rhs.getJarak() == lhs.getJarak() ? 0 : 1));
            }
        });
    }

    /**
     * Convert timeStamp into date String
     * 
     * @param timeStamp
     * @return
     */
    public static String convertTimestampToDate(long timeStamp, String format) {
        Timestamp stamp = new Timestamp(timeStamp * 1000);
        // SimpleDateFormat sf = new SimpleDateFormat("h:mm a");
        SimpleDateFormat sf = new SimpleDateFormat(format);
        Utils.TRACE("Utils", "convertTimestampToDate : " + sf.format(stamp));
        return sf.format(stamp);
    }

    /**
     * decode image from Base64 to Bitmap
     * 
     * @param base64
     * @return
     */
    public static Bitmap decodeBase64(String base64) {
        try {
            InputStream stream = new ByteArrayInputStream(Base64.decode(base64.getBytes()));
            return BitmapFactory.decodeStream(stream);
        } catch (IOException e) {
            // BaseApplication.getInstance().sentA
            Utils.TRACE("Utils", "decodeBase64 : " + e.getMessage());
        }
        return null;
    }

    public static Bitmap decodeFile(String filePath) {
        // Decode Image size
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        final int REQUIRED_SIZE = 512;

        int width_tmp = options.outWidth, height_tmp = options.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        BitmapFactory.Options options2 = new BitmapFactory.Options();
        options2.inSampleSize = scale;
        return BitmapFactory.decodeFile(filePath, options2);
    }

    public static String encodeImageToBASE64(Bitmap bmp) {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 80, bao);
        byte[] byteArray = bao.toByteArray();
        return Base64.encodeBytes(byteArray);
    }

    public static String encodeString(String text) {
        try {
            return URLEncoder.encode(text, "utf-8");
        } catch (UnsupportedEncodingException e) {
            Utils.TRACE("RateActivity", "encodeString : " + e.getMessage());
        }
        return null;
    }

}
